package com.yupi.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全量同步帖子到 es
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
// 取消注释后，每次启动Springboot 项目时，会启动一次run方法
@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

    @Override
    public void run(String... args) {
        // 1.获取数据
        String json = "{\"searchText\":\"\",\"pageSize\":20,\"current\":1,\"reviewStatus\":1,\"needQueryBase\":true}";
        String result = HttpRequest.post("https://api.codefather.cn/api/course/list/page/vo")
                .body(json)
                .execute().body();
        System.out.println(result);

        // 2.json转对象
        Map<String, Object> map = JSONUtil.toBean(result, Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) data.get("records");
        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject tmpRecord = (JSONObject) record;
            Post post = new Post();
            post.setTitle(tmpRecord.getStr("title"));
            post.setContent(tmpRecord.getStr("content"));
            JSONArray tags = new JSONArray(tmpRecord.get("tags"));
            List<String> tagsList = tags.toList(String.class);
            post.setTags(JSONUtil.toJsonStr(tagsList));
            post.setUserId(1L);
            postList.add(post);
        }
        System.out.println(map);
        // 3. 数据入库
        // 过滤已存在的标题
        List<String> existingTitles = postService.list().stream()
                .map(Post::getTitle)
                .collect(Collectors.toList());

        List<Post> newPosts = postList.stream()
                .filter(post -> !existingTitles.contains(post.getTitle()))
                .collect(Collectors.toList());

        if (newPosts.isEmpty()) {
            log.info("没有新的帖子需要入库");
        }

        boolean success = postService.saveBatch(newPosts);
        log.info("新增{}条帖子，过滤{}条重复数据", newPosts.size(),
                postList.size() - newPosts.size());

        if (success) {
            log.info("获取初始化帖子列表成功。条数 = {}", postList.size());
        } else {
            log.error("获取初始化帖子列表失败");
        }
    }
}
